<?php
import("ORG.Util.Function");
import("@.Org.Utils");
import("@.Org.PackageTool");


class PackageAction extends CommonAction{	
	
	public function _initialize(){
		parent::_initialize();				
		$param           =    $this->_get('_URL_');
		$controller      =    $param[0];
		$action          =    $param[1];		
		//language
		$lang            =    L($action);  		
		$manage          =    L('manage');
		
		$this->assign("manage",$manage);
		$this->assign("current",$lang);
		$this->assign("lang",$lang);
	}

	/**
	 * 超值礼包列表
	 * Enter description here ...
	 */
	public function package_list(){
			
	    /*$sort_flag  = sort_flag($packages['filter']);
	    $this->assign($sort_flag['tag'], $sort_flag['img']); // 默认排序字段*/
	
	    $sql_packages_list 			= 	get_sql_package_list();
	    $param = array(
				'result'	=> $sql_packages_list,			//分页用的数组或sql
				'listvar'	=> 'package_list',				//分页循环变量
				'listRows'	=> 10,							//每页记录数
				//'parameter'=>'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'	=> 'content',	    			//ajax更新内容的容器id，不带#
				'pagesId'	=> 'page',						//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'	=> 'Package:package_list',		//ajax更新模板
		);		
	    $this->page_package_list($param);
		
		$this->display('package_list');
	}
	
	/**
	 * 超值礼包列表分页
	 * Enter description here ...
	 * @param unknown_type $param
	 */
	public function page_package_list($param){
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		//================================================格式化数据		
	    foreach ($voList AS $key => $val){
	        $voList[$key]['start_time'] 		= 	local_date($GLOBALS['_CFG']['time_format'], $val['start_time']);
	        $voList[$key]['end_time']   		= 	local_date($GLOBALS['_CFG']['time_format'], $val['end_time']);
	        $info 								=	unserialize($row[$key]['ext_info']);
	        unset($voList[$key]['ext_info']);
	        if ($info){
	            foreach ($info as $info_key => $info_val){
	                $voList[$key][$info_key] 	= 	$info_val;
	            }
	        }
	    }	    		
		//================================================格式化数据
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
	
	/**
	 * 添加超值礼包
	 * Enter description here ...
	 */
	public function add_package(){
		
		$GoodsModel				=	new GoodsModel();
	    /* 组合商品 */
	    $group_goods_list 		= 	array();
	    $sql 					= 	"DELETE FROM " .'ybr_package_goods' .
	            					" WHERE package_id = 0 AND admin_id = '$_SESSION[admin_id]'";
	
	    M()->query($sql);
	
	    /* 初始化信息 */
	    $start_time 			= 	local_date('Y-m-d H:i');
	    $end_time   			= 	local_date('Y-m-d H:i', strtotime('+1 month'));
	    $package     			= array(
	    	'package_price'	=> '',
	    	'start_time' 	=> $start_time,
	    	'end_time' 		=> $end_time
	   	);
	
	    $this->assign('package',      	$package);
	    $this->assign('cat_list',    	$GoodsModel->cat_list());
	    $this->assign('brand_list',   	get_brand_list());
	    $this->assign('form_action',  	'insert');
	    $this->assign('action',  		'add_package_ok');
	
		$this->display('package_info');
	}
	
	/**
	 * 处理添加超值礼包
	 * Enter description here ...
	 */
	public function add_package_ok(){
		
		$CommonModel	=	new CommonModel();
		
	    $sql 			= 	"SELECT COUNT(*) ".
	           				" FROM " . 'ybr_goods_activity'.
	           				" WHERE act_type='" . GAT_PACKAGE . "' AND act_name='" . $_POST['package_name'] . "'" ;
	    if ($CommonModel->getOne($sql)){
	        //sys_msg(sprintf($_LANG['package_exist'],  $_POST['package_name']) , 1);
	        $this->error(L('package_exist'));
	    }
	
	
	    /* 将时间转换成整数 */
	    $_POST['start_time'] 		= 	local_strtotime($_POST['start_time']);
	    $_POST['end_time']   		= 	local_strtotime($_POST['end_time']);
	
	    /* 处理提交数据 */
	    if (empty($_POST['package_price'])){
	        $_POST['package_price'] = 	0;
	    }
	
	    $info 						= 	array('package_price'=>$_POST['package_price']);
	
	    /* 插入数据 */
	    $record 					= 	array(
						    				'act_name'		=>$_POST['package_name'],
						    				'act_desc'		=>$_POST['desc'],
						                    'act_type'		=>GAT_PACKAGE, 
						                    'start_time'	=>$_POST['start_time'],
						                    'end_time'		=>$_POST['end_time'], 
						                    'is_finished'	=>0, 
						                    'ext_info'		=>serialize($info)
	    								);
	
	    $CommonModel->AutoExecute('goods_activity',$record,'INSERT');
	
	    /* 礼包编号 */
	    $package_id 				= 	$CommonModel->insert_id();
	
	    handle_packagep_goods($package_id);
	
	    admin_log($_POST['package_name'],'add','package');
	    
		$this->success("操作成功",U('package/package_list'));
	}
	
	/**
	 * 修改礼包信息
	 * Enter description here ...
	 * 
	 */
	public function mod_package(){
	
		$GoodsModel				=	new GoodsModel();
		
	    $package            	= 	get_package_info($_REQUEST['id']);
	    $package_goods_list 	= 	get_package_goods($_REQUEST['id']); // 礼包商品
	
	    $this->assign('package',           	$package);
	    $this->assign('cat_list',     		$GoodsModel->cat_list());
	    $this->assign('brand_list',   		get_brand_list());
	    $this->assign('form_action',       	'update');
	    $this->assign('package_goods_list', $package_goods_list);
	    
	    $this->assign('form_action',  	'update');
	    $this->assign('action',  		'mod_package_ok');
		
		$this->display('package_info');
	}
	
	/**
	 * 处理修改超值礼包
	 * Enter description here ...
	 */
	public function mod_package_ok(){
		
		$CommonModel			=	new CommonModel();
		
	    /* 将时间转换成整数 */
	    $_POST['start_time'] 	= 	local_strtotime($_POST['start_time']);
	    $_POST['end_time']   	= 	local_strtotime($_POST['end_time']);
	
	    /* 处理提交数据 */
	    if (empty($_POST['package_price'])){
	        $_POST['package_price'] = 0;
	    }
	
	    /* 检查活动重名 */
	    $sql 					= 	"SELECT COUNT(*) ".
	           						" FROM " . 'ybr_goods_activity' .
	           						" WHERE act_type='" . GAT_PACKAGE . "' AND act_name='" . $_POST['package_name'] . "' AND act_id <> '" .  $_POST['id'] . "'" ;
	    if ($CommonModel->getOne($sql)){
	        //sys_msg(sprintf($_LANG['package_exist'],  $_POST['package_name']) , 1);
	        $this->error( sprintf( L('package_exist'),  $_POST['package_name']) );
	    }
	
	
	    $info 					= 	array('package_price'=>$_POST['package_price']);
	
	    /* 更新数据 */
	    $record 				= 	array(
	    								'act_name' 		=> $_POST['package_name'], 
	    								'start_time' 	=> $_POST['start_time'], 
	    								'end_time' 		=> $_POST['end_time'],
	                    				'act_desc' 		=> $_POST['desc'], 
	                    				'ext_info'		=> serialize($info)
	    							);
	    $CommonModel->autoExecute('goods_activity', $record, 'UPDATE', "act_id = '" . $_POST['id'] . "' AND act_type = " . GAT_PACKAGE );
	
	    admin_log($_POST['package_name'],'edit','package'); // 记录操作
	    
		$this->success("操作成功",U('package/package_list'));
	}	
	
	/**
	 * 删除礼包
	 * Enter description here ...
	 */
	public function remove_package(){
		import("@.Plugs.Exchange");
		
		$exc 		= 	new exchange("ybr_goods_activity" ,null, 'act_id', 'act_name');
	
	    $id 		= 	intval($_GET['id']);	
	    $exc->drop($id);
	
	    $sql 		=	"DELETE FROM " . 'ybr_package_goods' .
	            		" WHERE package_id='$id'";
	   	M()->query($sql);
	
	    $this->success("操作成功",U('package/package_list'));
	}
	
	
	/**
	 * 搜索商品
	 * Enter description here ...
	 */
	public function search_goods(){
	    $filters 		= 	$_GET['JSON'];
	
	    $arr 			= 	get_goods_list($filters);
	
	    $opt 			= 	array();
	    foreach ($arr AS $key => $val){
	        $opt[$key] = array('value' => $val['goods_id'],
	                        'text' => $val['goods_name'],
	                        'data' => $val['shop_price']);
	
	        $opt[$key]['products'] 	= 	get_good_products($val['goods_id']);
	    }
		$return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
	   	$this->ajaxReturn($return);
	}
	
	/**
	 * 添加礼包商品
	 * Enter description here ...
	 */
	public function add_package_goods(){
	
	    $fittings   		= 	$_GET['add_ids'];
	    $arguments  		= 	$_GET['JSON'];
	    $package_id 		= 	$arguments[0];
	    $number     		= 	$arguments[1];
	
	    foreach ($fittings AS $val){
	        $val_array 		= 	explode('_', $val);
	        if (!isset($val_array[1]) || $val_array[1] <= 0){
	            $val_array[1] 	= 	0;
	        }
	
	        $sql 			= 	"INSERT INTO " . 'ybr_package_goods' . " (package_id, goods_id, product_id, goods_number, admin_id) " .
	                			"VALUES ('$package_id', '" . $val_array[0] . "', '" . $val_array[1] . "', '$number', '$_SESSION[admin_id]')";
	        M()->query($sql);
	    }
	
	    $arr 				= 	get_package_goods($package_id);
	    $opt 				= 	array();
	
	    foreach ($arr AS $val){
	        $opt[] = array('value'      => $val['g_p'],
	                        'text'      => $val['goods_name'],
	                        'data'      => '');
	    }
		$return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
	    /*clear_cache_files(); // 删除缓存*/
	    $this->ajaxReturn($return);
	}
	
	/**
	 * 删除礼包商品
	 * Enter description here ...
	 */
	public function drop_package_goods(){
	
	    $fittings   		=	$_GET['drop_ids'];
	    $arguments  		= 	$_GET['JSON'];
	    $package_id 		=	$arguments[0];
	
	    $goods  			= 	array();
	    $g_p    			= 	array();
	    foreach ($fittings AS $val){
	        $val_array 		= 	explode('_', $val);
	        if (isset($val_array[1]) && $val_array[1] > 0){
	            $g_p['product_id'][] 	= 	$val_array[1];
	            $g_p['goods_id'][] 		= 	$val_array[0];
	        }
	        else{
	            $goods[] 				= 	$val_array[0];
	        }
	    }
	
	    if (!empty($goods)){
	        $sql 			= 	"DELETE FROM " . 'ybr_package_goods' .
	                			" WHERE package_id='$package_id' AND " . db_create_in($goods, 'goods_id');
	        if ($package_id == 0){
	            $sql 		.= 	" AND admin_id = '$_SESSION[admin_id]'";
	        }
	        M()->query($sql);
	    }
	
	    if (!empty($g_p)){
	        $sql 			= 	"DELETE FROM " .'ybr_package_goods' .
	                			" WHERE package_id='$package_id' AND " .db_create_in($g_p['goods_id'], 'goods_id') . " AND " . db_create_in($g_p['product_id'], 'product_id');
	        if ($package_id == 0){
	            $sql 		.= 	" AND admin_id = '$_SESSION[admin_id]'";
	        }
	        M()->query($sql);
	    }
	
	    $arr 				= 	get_package_goods($package_id);
	    $opt 				= 	array();
	
	    foreach ($arr AS $val){
	        $opt[] = array('value'      => $val['goods_id'],
	                        'text'      => $val['goods_name'],
	                        'data'      => '');
	    }
	
	    /*clear_cache_files(); // 删除缓存*/		
		$return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
	    /*clear_cache_files(); // 删除缓存*/
	    $this->ajaxReturn($return);
	}
	
	
	
	
	
	
	
	
	
}







